import kk from 'kokos'

cc.Class({
    extends: cc.Component,

    onLoad() {
        const event = kk.event
        const eventEnum = kk.constant.EVENT
        event.on(eventEnum.refreshPower, this.refreshPowerView, this)

        this.lastPower = 0
        this.awardValue = 10

        this.refreshPowerView()
    },

    onDestroy() {
        const event = kk.event
        const eventEnum = kk.constant.EVENT
        event.off(eventEnum.refreshPower, this.refreshPowerView, this)
    },

    // 减体力的动画
    playSubPowerAction() {
        return new Promise((resolve, reject) => {
            const icon = this.node.getChildByName('icon_power')
            const newIcon = cc.instantiate(icon)
            const iconAction = kk.action.iconJumpAction()
            const finished = cc.callFunc((target) => {
                newIcon.destroy()
                resolve()
            }, this)
            const allSeq = cc.sequence(iconAction, finished)

            newIcon.parent = icon
            newIcon.setPosition(0, 0)

            newIcon.runAction(allSeq)
        })
    },

    // 体力值变化的时候播放动画
    playChangePowerAction() {
        const icon = this.node.getChildByName('icon_power')
        const action = kk.action.windowOpenAction()

        icon.runAction(action)
    },

    // 刷新体力数值显示
    refreshPowerView() {
        const powerLabel = this.node.getChildByName('label').getComponent(cc.Label)
        const timeNode = this.node.getChildByName('updateTime')
        const { power, powerCycles } = kk.baseData
        const { upperLimit } = kk.config.power
        const powerIsFull = power >= upperLimit

        if (power !== this.lastPower) {
            this.playChangePowerAction()
        }
        this.lastPower = power

        powerLabel.string = `${power} / ${upperLimit}`

        timeNode.active = !powerIsFull
        !powerIsFull ? timeNode.getComponent(cc.Label).string = kk.time.formatSeconds(powerCycles) : null
    },

    handleAdd() {

    },

});